#ifndef CRITICAL_SECTION_H_
#define CRITICAL_SECTION_H_

#include <windows.h>
 
class CriticalSection
{
    //disable Copying
private:
    CriticalSection(const CriticalSection& rhs){}
    CriticalSection& operator=(const CriticalSection& rhs){}
public:
        CriticalSection()
        { 
                InitializeCriticalSection( &m_cs ); 
        }
 
        ~CriticalSection()
        {
                DeleteCriticalSection( &m_cs ); 
        }
 
 
        void Lock()
        { 
                EnterCriticalSection( &m_cs ); 
        }

        void Unlock()
        { 
                LeaveCriticalSection( &m_cs ); 
        }
 
protected:
       // the critical section itself
    mutable CRITICAL_SECTION m_cs;
};
 /*     Example Usage:
        we assume that m_cs
        is a private variable, and we use it to protect
        'this' from being accessed while we need safe access to a resource
        
       --->code that does not need resource locking
       {
              ScopedCriticalSection I_am_locked( m_cs);     
              <---code that needs thread locking
       }I_am_locked->dtr is called
       --->code that does not need resource locking
*/
class ScopedCriticalSection
{
    //disable Copying
private:
    ScopedCriticalSection(const ScopedCriticalSection& rhs);
    ScopedCriticalSection& operator=(const ScopedCriticalSection& rhs);
public:
        ScopedCriticalSection( CriticalSection & csResource)
                : m_csResource( csResource)
        {
                m_csResource.Lock();
        }
        ~ScopedCriticalSection()
        {
                m_csResource.Unlock();
        }
private:
       // the Critical Section for this resource
       CriticalSection & m_csResource;
};

#endif // CRITICAL_SECTION_H_